<template>
  <!-- 新增全局背景层 -->
  <view class="bg-layer"></view>
  
  <!-- 用户信息卡片 -->
  <view class="user-card">
    <view class="card-bg"></view>
    <image class="avatar" :src="user.avatar || '/static/default-avatar.png'" mode="aspectFill" />
    <view class="user-info">
      <text class="user-name">{{ user.name }}</text>
      <view class="meta-container">
        <view class="meta-badge">
          <uni-icons type="diamond" size="14" color="#60a5fa" />
          <text>{{ user.role }}</text>
        </view>
        <view class="meta-item">
          <uni-icons type="coin" size="16" color="#60a5fa" />
          <text>积分：{{ user.points || 0 }}</text>
        </view>
        <view class="divider"></view>
        <view class="meta-item">
          <uni-icons type="calendar-check" size="16" color="#60a5fa" />
          <text>已连续签到{{ user.consecutive_days || 0 }}天</text>
        </view>
      </view>
    </view>
  </view>

    <!-- 签到区域（增加粒子动效） -->
    <view class="checkin-section">
      <view class="particles">
        <view v-for="i in 8" :key="i" class="particle" :style="particleStyle(i)"></view>
      </view>
      <button
        class="checkin-button"
        :class="{ 
          'pulse': !isCheckedIn && !checkingIn,
          'checked': isCheckedIn,
          'checking': checkingIn
        }"
        @click="checkin"
        :disabled="checkingIn || isCheckedIn"
      >
        <view class="button-content">
          <template v-if="checkingIn">
            <view class="spinner"></view>
            <text>签到中</text>
          </template>
          <template v-else-if="isCheckedIn">
            <uni-icons type="checkmark" size="20" color="#fff" />
            <text>已签到</text>
          </template>
          <template v-else>
            <uni-icons type="calendar" size="20" color="#fff" />
            <text>每日签到</text>
            <text class="bonus-tip">+{{ checkinPoints }}积分</text>
          </template>
        </view>
      </button>
      <view class="streak-container">
        <view 
          v-for="day in 7" 
          :key="day"
          class="streak-day"
          :class="{ 'active': day <= (user.consecutive_days || 0) }"
        ></view>
      </view>
    </view>

    <!-- 排行榜（增加3D翻转效果） -->
    <view class="rankings-section">
      <swiper 
        class="swiper" 
        :autoplay="true" 
        :interval="5000"
        :circular="true"
        @change="swiperChange"
      >
        <swiper-item 
          v-for="(ranking, index) in rankings" 
          :key="index"
          class="swiper-item"
          :class="{ 'active': currentSwiperIndex === index }"
        >
          <view class="ranking-card">
            <view class="card-header">
              <text class="title">{{ ranking.title }}</text>
              <view class="medal">
                <text>TOP 5</text>
              </view>
            </view>
            <scroll-view scroll-y class="ranking-list">
              <view 
                v-for="(item, idx) in ranking.items.slice(0, 5)" 
                :key="idx"
                class="ranking-item"
                :class="{
                  'rank-1': idx === 0,
                  'rank-2': idx === 1,
                  'rank-3': idx === 2,
                  'current': item.isCurrentUser
                }"
              >
                <view class="crown" v-if="idx < 3"></view>
                <text class="rank">{{ idx + 1 }}</text>
                <text class="name">{{ item.name }}</text>
                <text class="value">{{ item.value || '无数据' }}</text>
                <view class="progress-bar">
                  <view 
                    class="progress" 
                    :style="{ width: `${Math.min(item.value/maxValues[index]*100, 100)}%` }"
                  ></view>
                </view>
              </view>
            </scroll-view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 导航按钮（增加悬浮效果） -->
    <view class="nav-grid">
      <view 
        v-for="(item, index) in navItems" 
        :key="index"
        class="nav-item"
        :class="'nav-' + index"
        @click="navigateTo(item.url)"
        @touchstart="navHover(index, true)"
        @touchend="navHover(index, false)"
        hover-class="none"
      >
        <view class="icon-box">
          <view class="icon-bg"></view>
          <image 
            class="icon" 
            :src="'/static/icons/nav-' + index + (navActiveIndex === index ? '-active.svg' : '.svg')" 
            mode="aspectFit"
          />
        </view>
        <text>{{ item.text }}</text>
        <view class="hover-effect"></view>
      </view>
    </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      rankings: [],
      checkingIn: false,
      isCheckedIn: false,
      currentSwiperIndex: 0,
      navActiveIndex: -1,
      maxValues: [100, 30, 5000], // 各排行榜最大值
      navItems: [
        { text: '1v1 PK', url: '/pages/student/pk' },
        { text: '视频学习', url: '/pages/student/video' },
        { text: '错题本', url: '/pages/student/wrong-questions' }
      ],
      checkinPoints: 5 // 签到获得积分
    }
  },
  onLoad() {
    this.loadUserData();
	this.checkIfCheckedIn();
  },
  onShow() {
    this.getUserPoints();
    this.getRankings();
	
  },
  methods: {
    // 保持原有云函数调用不变
    loadUserData() {
      const user = uni.getStorageSync('user') || {};
      if (!user.id) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        uni.navigateTo({ url: '/pages/student/login' });
      } else {
        this.user = user;
        this.checkIfCheckedIn();
      }
    },
    
    async getUserPoints() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0) {
          this.user.points = res.result.data.points;
          this.user.consecutive_days = res.result.data.consecutiveDays;
          uni.setStorageSync('user', this.user);
        }
      } catch (e) {
        console.error('获取积分失败:', e);
      }
    },
    
    async checkin() {
      if (this.checkingIn || this.isCheckedIn) return;
      
      this.checkingIn = true;
      try {
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
        const todayEnd = todayStart + 24 * 60 * 60 * 1000 - 1;

        const checkRes = await uniCloud.callFunction({
          name: 'getUserCheckins',
          data: { user_id: this.user.id, start: todayStart, end: todayEnd }
        });

        if (checkRes.result.count > 0) {
          this.isCheckedIn = true;
          return uni.showToast({ title: '今日已签到', icon: 'none' });
        }

        const res = await uniCloud.callFunction({
          name: 'checkin',
          data: { user_id: this.user.id }
        });

        if (res.result.code === 0) {
          this.user.points = res.result.data.points;
          this.user.consecutive_days = res.result.data.consecutiveDays;
          this.isCheckedIn = true;
          uni.setStorageSync('user', this.user);
          this.getRankings();
          this.checkinPoints = res.result.data.earnedPoints;
        }
        uni.showToast({
          title: res.result.code === 0 ? 
            `签到成功，获得 ${this.checkinPoints} 积分` : 
            res.result.msg,
          icon: res.result.code === 0 ? 'success' : 'none'
        });
      } catch (e) {
        uni.showToast({ title: '签到失败', icon: 'none' });
      } finally {
        this.checkingIn = false;
      }
    },
    
    async getRankings() {
      try {
        const res = await uniCloud.callFunction({ name: 'getRankings' });
        if (res.result.code === 0) {
          this.rankings = res.result.data.map(ranking => {
            return {
              ...ranking,
              items: ranking.items.map(item => {
                return {
                  ...item,
                  isCurrentUser: item.user_id === this.user.id
                }
              })
            };
          });
          // 计算各排行榜最大值
          this.maxValues = this.rankings.map(ranking => 
            Math.max(...ranking.items.map(item => item.value || 0), 1)
          );
        }
      } catch (e) {
        console.error('获取排行榜失败:', e);
      }
    },
    
    async checkIfCheckedIn() {
      try {
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
        const todayEnd = todayStart + 24 * 60 * 60 * 1000 - 1;

        const res = await uniCloud.callFunction({
          name: 'getUserCheckins',
          data: { user_id: this.user.id, start: todayStart, end: todayEnd }
        });
        this.isCheckedIn = res.result.count > 0;
      } catch (e) {
        console.error('检查签到状态失败:', e);
      }
    },
    
    navigateTo(url) {
      uni.navigateTo({ url });
    },
    
    // 新增UI交互方法
    cardScale(type) {
      this.animate('.user-card', [
        { transform: 'scale(1)' },
        { transform: `scale(${type ? 0.98 : 1})` }
      ], 200);
    },
    
    swiperChange(e) {
      this.currentSwiperIndex = e.detail.current;
    },
    
    navHover(index, isHover) {
      this.navActiveIndex = isHover ? index : -1;
      this.animate(`.nav-item.nav-${index}`, [
        { transform: `scale(${isHover ? 0.95 : 1})` }
      ], 200);
    },
    
    particleStyle(i) {
      const angle = (i / 8) * Math.PI * 2;
      return {
        transform: `rotate(${angle}rad) translateY(15px)`,
        opacity: this.isCheckedIn ? 0.6 : 0,
        transition: `opacity 0.3s ${i * 0.1}s`
      };
    },
    
    animate(selector, keyframes, duration) {
      const query = uni.createSelectorQuery().in(this);
      query.select(selector).boundingClientRect();
      query.exec(res => {
        if (res[0]) {
          res[0].animate(keyframes, { 
            duration,
            fill: 'forwards' 
          });
        }
      });
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
.container {
  position: relative;
  padding: 20px;
  min-height: 100vh;
  z-index: 1;
}

.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 40vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 20% 20%;
}

/* 用户卡片 - 科技蓝渐变风格 */
.user-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 18px;
  background: rgba(255, 255, 255, 0.28); /* 半透明白色玻璃基底 */
  border-radius: 18px;
  margin: 16px;
  overflow: hidden;
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 10px 30px rgba(74, 144, 226, 0.3), /* 与背景同色系阴影 */
    inset 0 1px 1px rgba(255, 255, 255, 0.4);
  transition: all 0.3s ease;
}

.user-card:active {
  transform: scale(0.98);
  box-shadow: 0 5px 15px rgba(23, 42, 58, 0.4);
}

.card-bg {
  position: absolute;
  top: 0;
  right: 0;
  width: 70%;
  height: 100%;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.15) 0%,
    transparent 60%
  );
}

/* 头像样式 */
.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-right: 16px;
  border: 2px solid rgba(255, 255, 255, 0.7);
  box-shadow: 
    0 0 20px rgba(255, 255, 255, 0.3),
    inset 0 0 10px rgba(255, 255, 255, 0.2);
  z-index: 1;
}

/* 文字配色方案 */
.user-name {
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}


.meta-container {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.meta-badge {
  background: #FFD700;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 11px;
  color: #ffffff;
  display: flex;
  align-items: center;
  gap: 4px;
  border: 1px solid rgba(100, 181, 246, 0.5);
  text-shadow: none;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: rgba(200, 220, 240, 0.9);
  gap: 4px;
}

.divider {
  width: 1px;
  height: 16px;
  background: rgba(100, 181, 246, 0.3);
}

/* 签到区域 */
.checkin-section {
  position: relative;
  margin-bottom: 24px;
  text-align: center;
}

.particles {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
}

.particle {
  position: absolute;
  width: 6px;
  height: 6px;
  background: #FFD700;
  border-radius: 50%;
  transform-origin: center;
}

.checkin-button {
  display: inline-block;
  padding: 0;
  border: none;
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  color: white;
  border-radius: 30px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 8px 0px rgba(74, 144, 226, 0.3);
  transition: all 0.3s;
}

.checkin-button.pulse {
  animation: pulse 2s infinite;
}

.checkin-button.checked {
  background: #e0e0e0;
  color: #9e9e9e;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.checkin-button.checking {
  opacity: 0.8;
}

.button-content {
  padding: 14px 28px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.bonus-tip {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 8px;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255,255,255,0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
}

.streak-container {
  display: flex;
  justify-content: center;
  gap: 6px;
  margin-top: 12px;
}

.streak-day {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  background: #e0e0e0;
  transition: all 0.3s;
}

.streak-day.active {
  background: #FFD700;
  transform: translateY(-2px);
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(74, 144, 226, 0.4); }
  70% { box-shadow: 0 0 0 12px rgba(74, 144, 226, 0); }
  100% { box-shadow: 0 0 0 0 rgba(74, 144, 226, 0); }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 排行榜 */
.rankings-section {
  margin-bottom: 24px;
}

.swiper {
  height: 280px;
}

.swiper-item {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  transform: scale(0.95);
  opacity: 0.8;
}

.swiper-item.active {
  transform: scale(1);
  opacity: 1;
}

.ranking-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 16px;
  height: 100%;
  box-shadow: 0 6px 18px rgba(0,0,0,0.05);
  backdrop-filter: blur(10px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.medal {
  background: #FFD700;
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.ranking-list {
  height: 220px;
}

.ranking-item {
  display: grid;
  grid-template-columns: 24px 1fr auto;
  align-items: center;
  padding: 10px 0;
  position: relative;
}

.ranking-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.05) 50%, rgba(0,0,0,0) 100%);
}

.rank {
  font-weight: bold;
  color: #666;
  text-align: center;
}

.rank-1 .rank { color: #FFD700; }
.rank-2 .rank { color: #C0C0C0; }
.rank-3 .rank { color: #CD7F32; }

.name {
  padding: 0 12px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.value {
  font-weight: 500;
  color: #4a90e2;
}

.progress-bar {
  grid-column: 1 / -1;
  height: 4px;
  background: rgba(0,0,0,0.05);
  border-radius: 2px;
  margin-top: 6px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4a90e2, #5aa1ff);
  border-radius: 2px;
  transition: width 1s;
}

.crown {
  position: absolute;
  top: -8px;
  left: 20px;
  width: 16px;
  height: 12px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="%23FFD700" d="M576 136c0 22.09-17.91 40-40 40h-64v304c0 8.837-7.163 16-16 16H120c-8.837 0-16-7.163-16-16V176H40c-22.09 0-40-17.91-40-40V72c0-22.09 17.91-40 40-40h120c22.09 0 40 17.91 40 40v16h192V72c0-22.09 17.91-40 40-40h120c22.09 0 40 17.91 40 40v64z"/></svg>');
  background-size: contain;
  background-repeat: no-repeat;
}

.current {
  background: rgba(74, 144, 226, 0.05);
  border-radius: 8px;
  margin: 0 -8px;
  padding: 0 8px;
}

/* 导航网格 */
.nav-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.nav-item {
  position: relative;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px 0;
  text-align: center;
  box-shadow: 0 6px 12px rgba(0,0,0,0.05);
  overflow: hidden;
  transition: all 0.3s;
}

.icon-box {
  position: relative;
  width: 48px;
  height: 48px;
  margin: 0 auto 8px;
}

.icon-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(74, 144, 226, 0.1);
  transform: scale(0.9);
  transition: all 0.3s;
}

.icon {
  position: relative;
  width: 60%;
  height: 60%;
  margin: 20%;
}

.hover-effect {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(255,255,255,0.2) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s;
}

.nav-item:active .icon-bg {
  transform: scale(1.1);
  background: rgba(74, 144, 226, 0.2);
}

.nav-item:active .hover-effect {
  opacity: 1;
}

/* 导航按钮个性化 */
.nav-0 {
  color: #FF5252;
}
.nav-1 {
  color: #4CAF50;
}
.nav-2 {
  color: #9C27B0;
}
</style>